﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace LoveNote.Core.Helpers
{
    /// <summary>
    /// JSON文件读写
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 读JSON文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T Load<T>(string path)
        {
            if (!File.Exists(path))
            {
                return default(T);
            }

            string content = File.ReadAllText(path);
            return JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        /// 将对象写成JSON文件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fullName"></param>
        /// <param name="indented"></param>
        public static string Write(object obj, string fullName, bool indented = false)
        {
            Newtonsoft.Json.Formatting f = indented ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;
            var content = JsonConvert.SerializeObject(obj, f);
            File.WriteAllText(fullName, content);
            return content;
        }

        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepClone<T>(this T obj) where T : class
        {
            string json = Serialize(obj);
            return Deserialize<T>(json);
        }

        public static string Serialize(object obj, bool indented = false)
        {
            Newtonsoft.Json.Formatting f = indented ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;
            return JsonConvert.SerializeObject(obj, f);
        }

        public static T Deserialize<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}
